﻿using System;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;

public class XmlTools {
	// === Public =====================================================================================================
	public static XmlTools CreateInstance() {
		var instance = new XmlTools();
		return instance;
	}

	public static T Deserialize<T>(XmlDocument xmlDoc) {
		return Deserialize<T>(xmlDoc.DocumentElement);
	}

	public static T Deserialize<T>(XmlNode xmlNode) {
		return (T)Deserialize(xmlNode, typeof(T));
	}

	public static object Deserialize(XmlDocument xmlDoc, Type type) {
		return Deserialize(xmlDoc.DocumentElement, type);
	}

	public static object Deserialize(XmlNode xmlNode, Type type) {
		if (xmlNode == null) { 
			throw new ArgumentNullException("xmlNode");
		}
		if (type == null) {
			throw new ArgumentNullException("type");
		}
		var serializer = new XmlSerializer(type);
		var reader = new XmlNodeReader(xmlNode);
		try {
			return serializer.Deserialize(reader);
		} catch (Exception e) {
			Debug.LogException(e);
			return null;
		}
	}
}
